<?php
class Settings extends Dao
{
	private static $_instance = null;
	protected $_db = null, $_cache = null;
	
	protected function __construct()
	{
		parent::__construct();
	}
	
	public static function getInstance() 
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
	
	public function getListGroups()
	{
		try{
			//explain select distinct setting_group from tbl_settings;
			//explain select setting_group from tbl_settings group by setting_group order by setting_group desc
			
			$strSql = " SELECT setting_group FROM tbl_settings GROUP BY setting_group ORDER BY setting_group DESC ";
			$cmd = $this->_db->createCommand($strSql);			
			$arrResults = $cmd->queryAll();
			return $arrResults;
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
	
	public function getList(array $args = array(), $returnStyle = RETURN_ASSOC_ARRAY)
	{
		try{
			$defaults = array(
				'setting_group' => null
			);
			$args = $this->args_merge($defaults, $args);
			
			$strSql = " 	
						SELECT * 
						FROM tbl_settings
						WHERE setting_group = IFNULL(:group, setting_group)
					  ";
			$cmd = $this->_db->createCommand($strSql);	
			$cmd->bindParam(":group",$args['setting_group'],PDO::PARAM_STR);		
			$arrResults = $cmd->queryAll();
			if($returnStyle === RETURN_NUMERIC_ARRAY){
				$arrTemp = array();
				foreach($arrResults as $R){
					$arrTemp[$R['setting_code']] = $R['setting_value'];	
				}
				$arrResults = $arrTemp;
			}
			return $arrResults;
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
	
	public function get($id){
		try{
			$strSql = " 	
						SELECT setting_value 
						FROM tbl_settings
						WHERE setting_code = :id
					  ";
			$cmd = $this->_db->createCommand($strSql);	
			$cmd->bindParam(":id",$id,PDO::PARAM_STR);		
			$result = $cmd->queryScalar();
			return $result;
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());	
		}
	}
	
	public function update($id, $value){
		$args = array(
			'setting_value' => $value			
		);
		$cmd = $this->_db->createCommand();
		return $cmd->update('tbl_settings',$args, 'setting_code=:id', array(':id'=>$id));
	}
}